﻿using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading.Tasks;
using Zj.CourseManage.Domain.Events;

namespace Zj.CourseManage.Serialization.Json
{
    /// <summary>
    /// Use newtonsoft to extend message serializer
    /// </summary>
    public class MessageJsonSerializer : IMessageSerializer
    {
        public MessageJsonSerializer()
        {
            this.encode = Encoding.UTF8;
        }
        private readonly Encoding encode;
        public IEvent DeSerialize(byte[] value) 
        {
            return JsonConvert.DeserializeObject<IEvent>(encode.GetString(value));
        }

        public async Task<IEvent> DeSerializeAsync(byte[] value)
        {
            return await Task.Factory.StartNew(() =>
            {
                return JsonConvert.DeserializeObject<IEvent>(encode.GetString(value));
            });
        }

        public byte[] Serialize<TMessage>(TMessage message) where TMessage : IEvent
        {
            return encode.GetBytes(JsonConvert.SerializeObject(message));
        }

        public async Task<byte[]> SerializeAsync<TMessage>(TMessage message) where TMessage : IEvent
        {
            return await Task.Factory.StartNew(() =>
            {
                return encode.GetBytes(JsonConvert.SerializeObject(message));
            });
        }
    }
}
